package com.wang.ymcc.service.impl;

import com.google.code.kaptcha.Producer;
import com.wang.lwm.constents.RedisConstents;
import com.wang.lwm.dto.RegisterCodeInRedis;
import com.wang.lwm.result.JSONResult;
import com.wang.lwm.util.Base64;
import com.wang.ymcc.config.RuoYiConfig;
import com.wang.ymcc.dot.SmsCodeDto;
import com.wang.lwm.exception.GlobalException;
import com.wang.lwm.util.StrUtils;
import com.wang.lwm.util.VerifyCodeUtils;
import com.wang.ymcc.dot.bluckdto;
import com.wang.ymcc.properties.CacheConstants;
import com.wang.ymcc.properties.Constants;
import com.wang.ymcc.properties.SMSCodeProperties;
import com.wang.ymcc.redis.RedisCache;
import com.wang.ymcc.service.IBluckService;
import com.wang.ymcc.service.ICommonService;
import com.wang.ymcc.service.IMessageSmsService;
import com.wang.ymcc.service.ISysConfigService;
import com.wang.ymcc.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IMessageSmsService messageSmsService;

    @Autowired
    private SMSCodeProperties codeProperties;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IBluckService bluckService;
    /*
        图形验证码
     */

    @Override
    public String getImageCode(HttpServletResponse response){
        // 保存验证码信息
        String capStr = null, code = null;
        BufferedImage image = null;
        //生成key
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        // 生成验证码
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);

        //将验证码存入redis
        redisTemplate.opsForValue().set(verifyKey,code,5, TimeUnit.MINUTES);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return e.getMessage();
        }


        //生成一个图像的验证码
        String base64Str = Base64.encode(os.toByteArray());
        return base64Str;

    }

    /*
        手机验证码
     */
    @Override
    public void getSms(SmsCodeDto smscodedto) {
        //图形验证码
        String imageCode = smscodedto.getImageCode();
        //图形验证码的key值
        String imageCodeKey = smscodedto.getImageCodeKey();
        //手机号
        String mobile = smscodedto.getMobile();
        //校验值是否为空   使用注解
        if(StringUtils.isEmpty(imageCode)){
            throw new GlobalException("图形验证码不能为空");
        }
        if(StringUtils.isEmpty(imageCodeKey)){
            throw new GlobalException("图形验证码不存在");
        }
        if(StringUtils.isEmpty(mobile)){
            throw new GlobalException("手机号不能为空");
        }
        //校验黑名单手机号和ip是否存在 1.先去redis中查看是否存在缓存 2.有就用没有就查数据库然后进行缓存

        bluckdto bluckdto = bluckService.selectByphone(mobile);
        if(bluckdto!=null){
            throw new GlobalException("mobile");
        }
        //1.图像验证码的验证

        //2.准备一个验证码
        String code = StrUtils.getRandomString(codeProperties.getLength());
        //存放在redis里面的key
        String key = RedisConstents.REG_IN_REDIS_PREFIX+smscodedto.getMobile();
        //检查redis里面是否已经存放过
        RegisterCodeInRedis codeInRedis = (RegisterCodeInRedis) redisTemplate.opsForValue().get(key);
        if(codeInRedis!=null){
            //1.检查距离上次发送的时间间隔
            if ((System.currentTimeMillis()-codeInRedis.getTime())/1000<codeProperties.getInterval()) {
                throw  new GlobalException("手速太快，请稍后再试");
            }else {
                code=codeInRedis.getCode();
            }
        }
        //3.存储到redis里面
        /*
            3.1 导包
            3.2 配置yml
            3.3 注入redisTemplate对象
            3.4 组装key和 code
            key: [sms:18244444444]
            value:[code:16985156256]
         */
        //创建一个验证码放到redis里面
        RegisterCodeInRedis newCodeInRedis = new RegisterCodeInRedis(code,System.currentTimeMillis());
        redisTemplate.opsForValue().set(key,newCodeInRedis,5, TimeUnit.MINUTES);

        //4.发送验证码【没做】
        String sms = "您的验证码为："+code+"请在5分钟内使用。";
        System.out.println(sms);

        //5.存储到t_message_sms里面
        messageSmsService.save("用户注册",sms,smscodedto.getMobile());
    }
}
